﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Web.Services.Protocols;
using System.Web.Services;
using Crawler.MapMatch;


namespace DataWeb
{
    public partial class frmMain : Form
    {
        private string url = "http://www.longmirror.com/vi-vn/euro/football";
        private string url_sbobet = "http://www.longmirror.com/vi-vn/euro/football";
        public frmMain()
        {
            InitializeComponent();
            try
            {
                Service service = new Service();                
                MapMatchInfo all = service.Match_GetAll("mqhpb01777", "tttt9999","fsfsfdf" );
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(((object)ex).ToString() + "\r\n" + ex.StackTrace);
            }
           // webBrowser1.Navigate(this.url);
            //List<trandau> l = new trandau().getTranDau();
            //dataGridViewSuccess.DataSource = l;
            //l = getTDSBOBET();
            //HtmlWeb hw = new HtmlWeb();
            //HtmlAgilityPack.HtmlDocument htmlDoc = hw.Load(this.url_sbobet);
            //if (htmlDoc.DocumentNode != null)
            //{
                //foreach (HtmlNode text in htmlDoc.DocumentNode.SelectNodes("//tr/td/div/text()"))
                //{
                //    Console.WriteLine(text.InnerText);
                //}
            //}

           // string s = this.geturl1();

            //webBrowser1.
            //var web = new HtmlWeb();
            //var document = web.Load("http://example.com/page.html");
            //var page = document.DocumentNode;

            //foreach(var item in page.QuerySelectorAll("div"))
            //{
            //    var title = item.QuerySelector("h1:not(.share)").InnerText;
            //    var des = item.QuerySelector("p").InnerText;
            //    var a = item.QuerySelector("p:has(a)").InnerHtml;
            //}
            //string html = webRequest();
            
        }

        private void getAllMatch() {
            try
            { 
                
            }catch(Exception ex){
                MessageBox.Show(((object)ex).ToString() + "\r\n" + ex.StackTrace);
            }
        }

        


        private string geturl1(){
// used to build entire input
		StringBuilder sb  = new StringBuilder();

		// used on each read operation
		byte[]        buf = new byte[8192];

		// prepare the web page we will be asking for
		HttpWebRequest  request  = (HttpWebRequest)
			WebRequest.Create(this.url_sbobet);

		// execute the request
		HttpWebResponse response = (HttpWebResponse)
			request.GetResponse();

		// we will read data via the response stream
		Stream resStream = response.GetResponseStream();

		string tempString = null;
		int    count      = 0;

		do
		{
			// fill the buffer with data
			count = resStream.Read(buf, 0, buf.Length);

			// make sure we read some data
			if (count != 0)
			{
				// translate from bytes to ASCII text
				tempString = Encoding.ASCII.GetString(buf, 0, count);

				// continue building the string
				sb.Append(tempString);
			}
		}
		while (count > 0); // any more data to read?
        return sb.ToString();
        }

        private void btnS_Click(object sender, EventArgs e)
        {
            List<string> a;
            a = f2(txtS.Text);
            listBox1.DataSource = a;
            //a = f3(txtS.Text);
            //listBox2.DataSource = a;
        }

        public string getStrUrlRequest(string url) {
            string kq = "";
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(this.url);
            myRequest.Method = "GET";
            WebResponse myResponse = myRequest.GetResponse();

            StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
            kq = sr.ReadToEnd();

            sr.Close();
            myResponse.Close();
            return kq;
        }

        public void f1() 
        {
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(this.url + "#q=" + txtS.Text.Trim());
            myRequest.Method = "GET";
            WebResponse myResponse = myRequest.GetResponse();

            StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
            string result = sr.ReadToEnd();

            sr.Close();
            myResponse.Close();

            webBrowser1.Navigate(this.url + "#q=" + txtS.Text.Trim());
        }

        public List<trandau> getTDSBOBET() { 
            List<trandau> l = new List<trandau>();
            WebClient webclient = new WebClient();
            webclient.Encoding = Encoding.UTF8;
            webclient.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
            string html = webclient.DownloadString(url_sbobet);
            //string html = getStrUrlRequest(this.url);
            //string sourcestring = "<div  class=\"LiveMarket\"><div onmouseout=\"return $M('od').onMouseOverOut(event,1);\" onmouseover=\"return $M('od').onMouseOverOut(event,0);\" class=\"MarketT Open\" id=\"od-ma-1-5\"><div class=\"MarketHd\" title=\"Tải Lại\" id=\"bu:od:re:15\"><div title=\"Nhấp để mở rộng hoặc thu nhỏ\" class=\"SubHead\" id=\"bu:od:oc:ma:1:5\"><span>1X2</span></div><div id=\"refresh-icon-15\" class=\"league-refresh-icon\"></div></div><div class=\"MarketBd\"><div class=\"MarketLea\"><div title=\"Thêm vào danh mục yêu thích\" class=\"IconFav \" id=\"bu:od:afa:to:23798\"></div><div title=\"Bỏ ra khỏi danh mục yêu thích\" class=\"IconFavSel Hide\" id=\"bu:od:rfa:to:23798\"></div><div class=\"SubHeadT\">COPA BRIDGESTONE LIBERTADORES</div><div title=\"\" class=\"\"></div></div><table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class=\"Onex2\"><tbody><tr id=\"bu:od:or:17131450\"><td class=\"DateTime\"><div class=\"DateTimeDiv\"><div class=\"FrontIconS\"><div><a href=\"javascript:$M('od').onLiveCenter(1381159)\" class=\"IconLCs\" id=\"bu:od:go:lc:1381159:0\"></a></div></div><div class=\"DateTimeTxt\">2-2<br><font color=\"red\">2H 27'</font></div><div id=\"od-ex-st-17131450\" class=\"FrontIconB2 Vhide\"><a href=\"javascript:$M('od').onLiveCenter(1381159)\" title=\"Trung Tâm Trực tiếp \" class=\"IconLC\" id=\"bu:od:go:lc:1381159:1\"></a></div></div></td><td class=\"Fav\"><div title=\"Thêm vào danh mục yêu thích\" class=\"IconFav \" id=\"bu:od:afa:ev:1381159\"></div><div title=\"Bỏ ra khỏi danh mục yêu thích\" class=\"IconFavSel Hide\" id=\"bu:od:rfa:ev:1381159\"></div></td><td><a title=\"Independiente Jose Teran\" class=\"OddsTabL PriceUp \" href=\"javascript:$M('od').onPrice('s',17131450,'1',2.81)\" id=\"od-s-17131450-1\"><span class=\"OddsR\">2.81</span><span class=\"OddsL\">Independiente Jose Teran</span></a></td><td class=\"Draw\"><a class=\"OddsTabL PriceDown\" href=\"javascript:$M('od').onPrice('s',17131450,'x',1.79)\" id=\"od-s-17131450-x\"><span class=\"OddsR\">1.79</span><span class=\"OddsL\">Hòa</span></a></td><td><a title=\"Union Espanola\" class=\"OddsTabR  \" href=\"javascript:$M('od').onPrice('s',17131450,'2',6.00)\" id=\"od-s-17131450-2\"><span class=\"OddsR\">6.00</span><span class=\"OddsL\">Union Espanola</span></a></td><td class=\"Icons\"><a title=\"Xem tất cả các lọai cược của tôi\" class=\"IconMarkets\" id=\"bu:od:go:ev:1381159\" href=\"/vi-vn/euro/football/copa-bridgestone-libertadores/1381159/independiente-jose-teran-và-union-espanola\">5</a><div title=\"Xem thống kê\" class=\"IconStats\" id=\"bu:od:go:st:1381159\"></div></td></tr></tbody></table></div></div><div onmouseout=\"return $M('od').onMouseOverOut(event,1);\" onmouseover=\"return $M('od').onMouseOverOut(event,0);\" class=\"MarketT Open\" id=\"od-ma-1-1\"><div class=\"MarketHd\" title=\"Tải Lại\" id=\"bu:od:re:11\"><div title=\"Nhấp để mở rộng hoặc thu nhỏ\" class=\"SubHead\" id=\"bu:od:oc:ma:1:1\"><span>Kèo Châu Á</span></div><div id=\"refresh-icon-11\" class=\"league-refresh-icon\"></div></div><div class=\"MarketBd\"><div class=\"MarketLea\"><div title=\"Thêm vào danh mục yêu thích\" class=\"IconFav \" id=\"bu:od:afa:to:23798\"></div><div title=\"Bỏ ra khỏi danh mục yêu thích\" class=\"IconFavSel Hide\" id=\"bu:od:rfa:to:23798\"></div><div class=\"SubHeadT\">COPA BRIDGESTONE LIBERTADORES</div><div title=\"\" class=\"\"></div></div><table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class=\"Hdp\"><tbody><tr id=\"bu:od:or:17131445\"><td class=\"DateTime\"><div class=\"DateTimeDiv\"><div class=\"FrontIconS\"><div><a href=\"javascript:$M('od').onLiveCenter(1381159)\" class=\"IconLCs\" id=\"bu:od:go:lc:1381159:0\"></a></div></div><div class=\"DateTimeTxt\">2-2<br><font color=\"red\">2H 27'</font></div><div id=\"od-ex-st-17131445\" class=\"FrontIconB2 Vhide\" style=\"visibility: hidden;\"><a href=\"javascript:$M('od').onLiveCenter(1381159)\" title=\"Trung Tâm Trực tiếp \" class=\"IconLC\" id=\"bu:od:go:lc:1381159:1\"></a></div></div></td><td class=\"Fav\"><div title=\"Thêm vào danh mục yêu thích\" class=\"IconFav \" id=\"bu:od:afa:ev:1381159\"></div><div title=\"Bỏ ra khỏi danh mục yêu thích\" class=\"IconFavSel Hide\" id=\"bu:od:rfa:ev:1381159\"></div></td><td><a class=\"OddsTabL PriceUp \" href=\"javascript:$M('od').onPrice('s',17131445,'h',2.11)\" id=\"od-s-17131445-h\"><span class=\"OddsR\">2.11</span><span class=\"OddsM\">-0.25</span><span title=\"Independiente Jose Teran\" class=\"OddsL\">Independiente Jose Teran</span></a></td><td><a class=\"OddsTabR PriceDown \" href=\"javascript:$M('od').onPrice('s',17131445,'a',1.82)\" id=\"od-s-17131445-a\"><span class=\"OddsR\">1.82</span><span class=\"OddsM\">+0.25</span><span title=\"Union Espanola\" class=\"OddsL\">Union Espanola</span></a></td><td class=\"Icons\"><a title=\"Xem tất cả các lọai cược của tôi\" class=\"IconMarkets\" id=\"bu:od:go:ev:1381159\" href=\"/vi-vn/euro/football/copa-bridgestone-libertadores/1381159/independiente-jose-teran-và-union-espanola\">5</a><div title=\"Xem thống kê\" class=\"IconStats\" id=\"bu:od:go:st:1381159\"></div></td></tr><tr id=\"bu:od:or:17131444\"><td class=\"DateTime\"><div class=\"DateTimeDiv\"><div class=\"FrontIconS\"><div><a href=\"javascript:$M('od').onLiveCenter(1381159)\" class=\"IconLCs\" id=\"bu:od:go:lc:1381159:0\"></a></div></div><div class=\"DateTimeTxt\">2-2<br><font color=\"red\">2H 27'</font></div><div id=\"od-ex-st-17131444\" class=\"FrontIconB2 Vhide\" style=\"visibility: hidden;\"><a href=\"javascript:$M('od').onLiveCenter(1381159)\" title=\"Trung Tâm Trực tiếp \" class=\"IconLC\" id=\"bu:od:go:lc:1381159:1\"></a></div></div></td><td class=\"Fav\"><div title=\"Thêm vào danh mục yêu thích\" class=\"IconFav \" id=\"bu:od:afa:ev:1381159\"></div><div title=\"Bỏ ra khỏi danh mục yêu thích\" class=\"IconFavSel Hide\" id=\"bu:od:rfa:ev:1381159\"></div></td><td><a class=\"OddsTabL PriceUp \" href=\"javascript:$M('od').onPrice('s',17131444,'h',1.32)\" id=\"od-s-17131444-h\"><span class=\"OddsR\">1.32</span><span class=\"OddsM\">0.00</span><span title=\"Independiente Jose Teran\" class=\"OddsL\">Independiente Jose Teran</span></a></td><td><a class=\"OddsTabR PriceDown \" href=\"javascript:$M('od').onPrice('s',17131444,'a',3.50)\" id=\"od-s-17131444-a\"><span class=\"OddsR\">3.50</span><span class=\"OddsM\">0.00</span><span title=\"Union Espanola\" class=\"OddsL\">Union Espanola</span></a></td><td class=\"Icons\"><a title=\"Xem tất cả các lọai cược của tôi\" class=\"IconMarkets\" id=\"bu:od:go:ev:1381159\" href=\"/vi-vn/euro/football/copa-bridgestone-libertadores/1381159/independiente-jose-teran-và-union-espanola\">5</a><div title=\"Xem thống kê\" class=\"IconStats\" id=\"bu:od:go:st:1381159\"></div></td></tr></tbody></table></div></div></div>";
            string globalPattern = String.Format("<div[^>]*?class=([\"'])[^>]*{0}[^>]*\\1[^>]*>(.*?)</div>", "MarketT Open");
            //Regex re = new Regex(@"\<\s*div\b[^\>]+class\s*=\s*['""]SubHead['""][^\>]*\>(.+?)</table></div></div>");
            Regex re = new Regex(globalPattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
            //MatchCollection mc = Regex.Matches(html, "<div class=\"MarketT Open\"",RegexOptions.None);
            MatchCollection mc = re.Matches(html);
            int mIdx = 0;
            foreach (Match m in mc)
            {
                for (int gIdx = 0; gIdx < m.Groups.Count; gIdx++)
                {
                    //Console.WriteLine("[{0}][{1}] = {2}", mIdx, re.GetGroupNames()[gIdx], m.Groups[gIdx].Value);

                }
                mIdx++;
            }
            l = new trandau().getTranDau();
            return l;
        }
        public List<string> f2(string word) {
            List<string> l = new List<string>();
            WebClient webclient = new WebClient();           
            string url = string.Format("http://thesaurus.com/search?q={0}", word);
            string html = webclient.DownloadString(url);

            MatchCollection mc = Regex.Matches(html,"<span class=\"text\">\\s*(.+?)\\s*</span>",RegexOptions.Singleline);

            foreach (Match m in mc)
            { 
                string s = m.Groups[1].Value;
                l.Add(s);
            }
            return l;
        }


        /// <summary>
        /// This method relies heavily on thesaurus.com for synonym lookups. It is not completely reliable, but is deemed reliable enough in instances where you dont have your own thesaurus
        /// </summary>
        public static List<string> f3(string word)
        {
            string url = string.Format("http://thesaurus.com/search?q={0}", word);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                List<string> synonyms = new List<string>();
                StringBuilder data = new StringBuilder();
                string line;

                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {

                    //we know that the synonyms is in the upper-part of the html stream so we do not want to read the entire stream.
                    while ((line = reader.ReadLine()) != null)
                    {
                        var index = line.IndexOf("<span class=\"text\">");

                        if (index > 0)
                        {
                            index = index + "<span class=\"text\">".Length;
                            synonyms.Add(line.Substring(index).Replace("</span>", ""));
                        }

                        //break when we come to the Antonyms section of the page
                        if (line.Contains("container-info antonyms"))
                        {
                            break;
                        }
                    }
                }
                return synonyms;
            }
            else
            {
                return null;
            }
        }

        public string SendPost(string url, string postData)
        {
            string webpageContent = string.Empty;

            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);

                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                webRequest.Method = "POST";
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.ContentLength = byteArray.Length;

                using (Stream webpageStream = webRequest.GetRequestStream())
                {
                    webpageStream.Write(byteArray, 0, byteArray.Length);
                    webpageStream.Close();
                }

                using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
                    {
                        webpageContent = reader.ReadToEnd();
                        reader.Close();                        
                    }
                }
            }
            catch (Exception ex)
            {
                //throw or return an appropriate response/exception
            }

            return webpageContent;
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            string post = "login=nguyenthanhphuoc04@yahoo.com&passwdInp2=123456";
            string url = "https://app.getresponse.com/login.html?lang=en";
            string test = SendPost(url, post);
            MessageBox.Show(test);
        }

        public string webRequest(){
            try
            {

                // Create the request object

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.nowgoal.com/freeodds.aspx?t=comp");



                // Optionally, you can set HTTP-specific elements on

                // the request, such as the User-Agent header

                request.UserAgent = "Test Client version 1.0";



                // Issue the request

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();



                // Read the content

                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII);



                string content = reader.ReadToEnd();



                // Display the content to the console

                //Console.WriteLine(content);



                // Close the response

                response.Close();
                return content;
            }

            catch (WebException wex)
            {

                //Console.WriteLine(wex.ToString());

                // Check the status to see if there might be a response object

                if (wex.Status == WebExceptionStatus.ProtocolError)
                {

                    HttpWebResponse response = (HttpWebResponse)wex.Response;

                    //Console.WriteLine();

                    MessageBox.Show("The protocol error returned was '" + response.StatusCode.ToString() + "'.");

                    response.Close();

                }

            }
            return "";
        }

        public static string sendToServer(string url, string Request)
        {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                //HttpWebRequest class is used to Make a request to a Uniform Resource Identifier (URI). 
                request.ContentType = "application/x-www-form-urlencoded";
               // Set the ContentType property of the WebRequest.
                request.Method = "POST";
                byte[] byteArray = Encoding.UTF8.GetBytes(Request);
               // Set the ContentLength property of the WebRequest.
                request.ContentLength = byteArray.Length; 
               //Get the stream that holds request data by calling the GetRequestStream method.
                Stream dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                dataStream.Close();
                WebResponse response = request.GetResponse();
               // Get the stream containing content returned by the server.
                //Send the request to the server by calling GetResponse.
                dataStream = response.GetResponseStream();
               // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
               // Read the content.
                string Response = reader.ReadToEnd();
                //return the response
                return Response;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
            webBrowser1.Navigate(this.url_sbobet);
            //webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(OnDocumentCompleted);
        }

        protected void OnDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            //HtmlElement elemen = webBrowser1.Document
            //System.Windows.Forms.HtmlDocument doc = webBrowser1.Document;
            //HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            //doc.LoadHtml(this.webBrowser1.DocumentText);
            //doc.LoadHtml(((dynamic)this.webBrowser1.Document.DomDocument).documentElement.outerHTML);
            //doc.Load(webBrowser1.DocumentStream);
            //HtmlWindow window = webBrowser1.Document.Window;
            //string str = window.Document.Body.OuterHtml;
            //string classToFind = "LiveMarket";
            //string id = "panel-odds-display";
            //var nodes = doc.DocumentNode.SelectNodes("//div[@id='"+id+"']");
            //var allElementsWithClassFloat = doc.DocumentNode.SelectNodes(string.Format("//*[contains(@class,'{0}')]", classToFind));
            //foreach (HtmlElement el in doc.All){
            //    if (el.GetAttribute("className") == "MarketLea")
            //    {
                    
            //    }
            //}
        }

    }
}
